package com.lishem.leftgod.level1.class03;

public class Code_08_ZigZagPrintMatrix {


    private static void printMatrixZigZag(int[][] matrix) {
        if (matrix == null) {
            return;
        }

        int x1 = 0, x2 = 0, y1 = 0, y2 = 0;
        boolean flag = true;
        while (x1 < matrix[0].length && y2 < matrix.length) {
            printOneLine(matrix, x1, y1, x2, y2, flag);
            if (y1 == matrix.length - 1) {
                x1++;
            } else {
                y1++;
            }
            if (x2 == matrix[0].length - 1) {
                y2++;
            } else {
                x2++;
            }
            flag = !flag;
        }

    }

    private static void printOneLine(int[][] matrix, int x1, int y1, int x2, int y2, boolean flag) {
        if (flag) {
            // 从下往上
            while (y1 >= y2 && x1 <= x2) {
                System.out.print(matrix[y1--][x1++] + " ");
            }
        } else {
            while (y1 >= y2 && x1 <= x2) {
                System.out.print(matrix[y2++][x2--] + " ");
            }
        }
    }

    // 1 2 5 9 6 3 4 7 10 11 8 12
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12}};
        printMatrixZigZag(matrix);
    }

}
